﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using CoastalClimbing.Code;
using System.Data;
using System.Net;
using System.IO;
using System.Xml.Linq;
using InstaSharp;
using System.Collections.Specialized;

namespace CoastalClimbing
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                this.BindData();
        }

        private void BindData()
        {
            try
            {
                LatestBlurb blurb = DAL.GetLatestBlurb();
                litTitle.Text = "<span class='" + blurb.TitleStyle + "'>" + blurb.Title + "</span>";
                litMessage.Text = "<span class='" + blurb.MessageStyle + "'>" + blurb.Message + "</span>";
            }
            catch 
            {
                //gobble that shit up
            }
            try
            {
                List<RssFeedItem> prefeeds = (List<RssFeedItem>)Cache["CACHEDPREFEEDS"];                

                if (prefeeds == null)
                {
                    prefeeds = new List<RssFeedItem>();
                    var rssFeed = new Uri("http://www.climbing.com/news/hotflashes/rss/standard_rss.xml");
                    var request = (HttpWebRequest)WebRequest.Create(rssFeed);
                    request.Method = "Get";
                    var response = (HttpWebResponse)request.GetResponse();

                    using(var reader = new StreamReader(response.GetResponseStream()))
                    {
                        var feedContents = reader.ReadToEnd();

                        var document = XDocument.Parse(feedContents);

                        var posts = (from p in document.Descendants("item")
                                    select new
                                    {
                                        Description = p.Element("description").Value,
                                        Link = p.Element("link").Value,
                                        Title = p.Element("title").Value,
                                        //Date = p.Element("pubdate").Value
                                    }).ToList();

                        foreach (var item in posts)
                        {
                            RssFeedItem feedItem = new RssFeedItem();
                            feedItem.Description = item.Description;
                            feedItem.Link = item.Link;
                            feedItem.Title = item.Title;
                            //feedItem.PublishDate = Convert.ToDateTime(String.Format("{0:MM/dd/yyyy hh:mm tt}", DateTime.Parse(item.Date.Remove(item.Date.LastIndexOf(" ")))));
                          
                            prefeeds.Add(feedItem);
                        }
                    }


//                    prefeeds = RssManager.ReadFeed("http://www.climbing.com/news/hotflashes/rss/standard_rss.xml");
                    Cache.Insert("CACHEDPREFEEDS", prefeeds, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(1, 0, 0, 0));
                }

                dtlNews.DataSource = (from feed in prefeeds orderby feed.PublishDate descending select feed).Take(5);
                dtlNews.DataBind();
            }
            catch(Exception ex)
            {
                litNewsFail.Visible = true;
                litNewsFail.Text = "www.climbing.com is having a problem with their news feed. We will have this up and running once they get their act together.";
                //throw ex;
                //gobble that shit up
            }

            try
            {
                List<RssFeedItem> facebookfeeds = RssManager.ReadFeed("http://www.facebook.com/feeds/page.php?id=258584030851639&format=rss20");
                dtlFacebook.DataSource = (from feed in facebookfeeds orderby feed.PublishDate descending select feed).Take(5);
                dtlFacebook.DataBind();
            }
            catch
            {
                //gobble that shit up   
            }

            try
            {
                List<GalleryImage> images = (List<GalleryImage>)Cache["CACHEDIMAGES"];

                if (images == null)
                {
                    images = DAL.GalleryImageSelectSlideshow();
                    Cache.Insert("CACHEDIMAGES", images, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 60, 0));
                }

                rptImages.DataSource = images;
                rptImages.DataBind();
            }
            catch
            {
                //gobble that shit up
            }

            try
            {
                dtlRoutes.DataSource = DAL.RoutesSelectTopFour();
                dtlRoutes.DataBind();
            }
            catch
            {
                //gobble that shit up
            }

            try
            {
                dtlImages.DataSource = GetInstaCrap(); 
                dtlImages.DataBind();
            }
            catch(Exception ex)
            {
                litImages.Visible = true;
                litImages.Text = ex.Message;
                
                //"Looks like Instgram messed something up and you don't get to see any pretty pictures. We will be back up and running once they get their act together.";
                //throw ex;
                //gobble that shit up
            }
        }

        private List<InstaPic> GetInstaCrap()
        {
            var oAuthURI = "https://api.instagram.com/v1";
            var clientId = Common.Constants.INSTAGRAM_CLIENT_ID;
            var redirectURI = Common.Constants.INSTAGRAM_REDIRECT_URI;
            var clientSecret = Common.Constants.INSTAGRAM_CLIENT_SECRET;
            var login = Common.Constants.INSTAGRAM_LOGIN;
            var password = Common.Constants.INSTAGRAM_PASSWORD;

            var config = new InstaSharp.InstagramConfig(oAuthURI, "https://api.instagram.com/oauth", clientId, clientSecret, redirectURI);
            var unAuth = new InstaSharp.Endpoints.Tags.Unauthenticated(config);
            var pictures = unAuth.Recent("COASTALCLIMBING");
            dynamic dyn = Newtonsoft.Json.JsonConvert.DeserializeObject(pictures.Json);

            List<InstaPic> pics = new List<InstaPic>();
            
            foreach (var data in dyn.data)
            {
                InstaPic p = new InstaPic();
                p.Url = data.images.thumbnail.url.ToString();
                p.Comment = data.caption.text.ToString();
                p.InstagramUrl = data.link.ToString();

                pics.Add(p);                
            }

            int count = pics.Count - 6;
            pics.RemoveRange(6, count);

            return pics;
        }      
    }

    public class InstaPic
    {
        private string _url, _comment, _instagramUrl;

        public string Url
        {
            get {
                return _url;
            }
            set {
                _url = value;   
            }
        }
        public string Comment
        {
            get {
                return _comment;
            }
            set {
                _comment = value;   
            }
        }
        public string InstagramUrl
        {
            get {
                return _instagramUrl;
            }
            set {
                _instagramUrl = value;
            }
        }
    }
}